// radio事件委托, 切换不同的送餐方式来显示不同的选项、配送费、总价格
$(document).on('click', 'input[type="radio"]', function () {
    var name = $(this).data('name'),
        $inputs = $(this).parents('div.radio').find('input[type="radio"][data-name=' + name + ']'),
        target = $(this).data('target'),
        $cost = $('[data-name="cost"]'),
        cost = Number($cost[0].innerText.split('￥')[1]),
        $fare = $(document).find('div[data-name=fare]'),
        fare = Number($fare.find('.money').text().split('￥')[1]),
        picker = $(this).data('picker'),
        reset = $(this).data('reset'),
        that = this;

    if (picker) {
        if ($('.weui-picker-modal').length === 0) {
            $(picker).picker("open");
        }
    }

    if (reset) {
        $(reset).text('稍晚时间');
    }

    if ($(this).attr('checked')) {
        return false;
    }

    // input[checkbox] 勾选
    $.each($inputs, function () {
        if (that === this) {
            $(this).attr('checked', true);
        } else {
            $(this).attr('checked', false);
        }
    });

    if (target) {
        var $receipt = $('#receipt-place,#receipt-time'),
            $train = $('#train-place,#train-time');
        if (target === 'receipt') {
            $train.hide();
            $receipt.show();
        } else {
            $receipt.hide();
            $train.show();
        }
    }
});

// 渲染页面
var errmsg, productList = [], route = JSON.parse(sessionStorage.getItem('route')),
    init = sessionStorage.init ? JSON.parse(sessionStorage.init) : undefined,
    stationName = (sessionStorage.stationName || '深圳北') + '站',
    mul = function (a, b) {
        var c = 0,
            d = a.toString(),
            e = b.toString();
        try {
            c += d.split(".")[1].length;
        } catch (f) {
        }
        try {
            c += e.split(".")[1].length;
        } catch (f) {
        }
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    },
    add = function (a, b) {
        var c, d, e;
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
    };
// delivery = sessionStorage.delivery ? JSON.parse(sessionStorage.delivery) : undefined;

$.showLoading();
$.ajax({
    url: '/RailwayService/order/affirmOrder?merchantId=' + sessionStorage.merchantId + '&stationId=' + sessionStorage.stationId,
    type: 'GET',
    dataType: 'json',
    success: function (resp) {
        if (resp.success) {
            var user_info = resp.data['user'],
                cost = 0,
                cost_every,
                re = /[^\u4e00-\u9fa5]/,
                name = user_info.name ? user_info.name : user_info.nickName;

            // 设置商家坐在站点
            $('[data-name=station]').text(stationName);

            // 候车室位置选择
            initLocationPicker(resp.data['listDeliverAddress']);

            // 候车室时间选择
            initTimePicker();

            // 判断配送人员是否在线
            // if (!delivery) {
            //     $.alert('配送人员暂不在线，不支持点餐');
            // }

            // 判断是否从行程页面过来的
            if (init) {
                $(init.type).click();  // 选择送货类型
                $('#username').val(init.data.customerName); // 填充用户名
                $('#phone').val(init.data.customerPhoneNo); // 填充手机号
                $('#train-select').val(init.data.seat);  // 填充火车送货地址
                // 填充候车室收货地址
                if (init.data.address.deliverAddressId) {
                    $('#location-select').val(init.data.address.val).data('deliveraddressid', init.data.address.deliverAddressId);
                }
                // 填充候车室送达时间
                var $input = $(init.data.time.checkId);
                $input.prop('checked', true);
                $input.parents('label').find('span.font-orange').text(init.data.time.val);
            } else {
                // 填充用户名
                if (name) {
                    $('#username').val(re.test(name) ? '' : name);
                }

                // 填充手机号
                if (user_info.phoneNo) {
                    $('#phone').val(user_info.phoneNo);
                }

                $('#late_20').click();
            }

            // 火车上的配送时间
            $('#train-time').find('.weui-flex__item:last-child').text(route.aboardTime.split(':').map(
                function (x) {
                    return x.length < 2 ? '0' + x : x;
                }).join(':'));

            // 设置商家地址
            // $('.order-merchant span').text(resp.data['merchant'].address ? resp.data['merchant'].address : '商家暂未设置地址');

            // 渲染详细商品、生成购物车缓存
            var commodity = {};
            $.each(resp.data['listShoppingCart'], function () {
                cost_every = mul(this.price, this.count);
                cost = add(cost, cost_every);
                commodity[this.productId] = {num: this.count};

                $('div.order-accounts-bd').append($('#clone').clone().html().replace(
                    '__商品名称__', this.productName).replace(
                    '__商品数量__', this.count).replace('__商品价格__', cost_every));
                productList.push({productId: this.productId, quantity: this.count});
            });
            sessionStorage.setItem('shoppingCart', JSON.stringify(commodity));

            // 渲染配送费
            $('div.order-accounts-bd').append($('#clone').clone().html().replace(
                '__商品名称__', '配送费').replace('X__商品数量__', '').replace('__商品价格__', resp.data.distributionCosts).replace('tr', 'fare'));

            // 设置消费总价
            cost = add(cost, resp.data.distributionCosts);
            $('[data-name=cost]').text('￥' + cost);

            // 配送方式
            // if (order) {
            //     // 配送地址
            //     if (order.address) {
            //         $('#location-select').val(order.address);
            //     }
            //     $(order.typeId).click();
            //     // 配送时间
            //     $(order.timeId).click().parents('label').find('.font-orange').text(order.afterTime ? order.afterTime : order.latestServiceTime);
            //     sessionStorage.removeItem('Order');
            //     order = null;
            // }

            // 设置小推车图片
            $.each(resp.data['stationForImageRelaList'], function () {
                $('.pay-mask .map').append(`<img src="${String(this)}" alt="图片加载失败" style="color: #fff;">`);
            });

            // 删除支付页面session缓存
            sessionStorage.removeItem('init');
        }
        else {
            errmsg = resp.message;
        }
    },
    error: function (XHR) {
        errmsg = XHR.statusText;
    },
    complete: function () {
        $.hideLoading();
        if (errmsg) {
            $.toast(errmsg, 'forbidden');
            setTimeout(function () {
                history.back();
            }, 2500)
        }
    }
});

var initLocationPicker = function (address) {
    $("#location-select").picker({
        payOrder: true,
        title: "请选择您的收货地址",
        cols: [
            {
                textAlign: 'center',
                values: $.map(address, function (i) {
                    return i.address
                })
            }
        ],
        address: address,
        onClose: function (p) {
            $(p.params.input).attr('data-deliverAddressId', p.params.address[p.params.cols[0].activeIndex].deliverAddressId);
        }
    });
};

var initTimePicker = function () {
    var date = new Date(),
        min = date.getMinutes() + 20,
        hour = date.getHours(),
        hours = [],
        first_mins = [],
        normal_mins = [],
        remainder,
        index = 0,
        default_time = '';

    for (var i = 0; i <= 55; i += 5) {
        normal_mins.push(i > 5 ? String(i) : '0' + String(i));
    }

    if (min > 60) {
        hour += 1;
        min -= 60;
    }

    remainder = min % 5;

    if (remainder !== 0) {
        min += 5 - remainder;
    } else {
        min += 5;
    }

    if (min > 55) {
        hour++;
        first_mins = normal_mins;
    } else {
        while (min <= 55) {
            first_mins.push(min > 5 ? String(min) : '0' + String(min));
            min += 5;
        }
    }

    for (; hour < 24; ++hour) {
        hours.push(hour);
    }

    // 取得默认时间
    if (sessionStorage.getItem('route')) {
        var aboardTime = JSON.parse(sessionStorage.getItem('route')).aboardTime.split(':'),
            default_h = parseInt(aboardTime[0]),
            default_m = parseInt(aboardTime[1]);

        default_m -= 15;
        if ((default_h * 60 + default_m) > (hour * 60 + min)) {
            if (default_m < 0) {
                default_h -= 1;
                default_m += 60;
            }
            if (default_m < 10) {
                default_m = '0' + String(default_m);
            }
            default_time = String(default_h) + ':' + String(default_m);
        }
    }

    $("#last-time").val(default_time).picker({
        title: "请选择您的取货时间",
        time: true,
        onClose: function (picker) {
            $($(picker.params.input).data('target')).text(picker.value.join(':'));
        },
        cols: [
            {
                textAlign: 'center',
                values: hours,
                cssClass: 'time-picker',
                onChange: function (picker, value) {
                    var data,
                        idx = picker.cols[0].activeIndex;
                    // col2_value = picker.cols[1].value;
                    if ((idx !== 0 && index === 0) || (idx === 0 && index !== 0)) {
                        if (idx === 0) {
                            data = first_mins;
                        } else {
                            data = normal_mins;
                        }
                        picker.cols[1].replaceValues(data, data);
                        // $("#time-select").picker('setValue', [value, col2_value]);
                    }
                    index = idx;
                }
            },
            {
                textAlign: 'center',
                cssClass: 'time-picker',
                values: first_mins
            }
        ]
    });
};

// 获得时间
function getTime(date, offset) {
    var hour, min, time;
    if (date instanceof Object) {
        hour = date.getHours();
        min = date.getMinutes();
    } else {
        date = date.split(':');
        hour = date[0];
        min = date[1];
    }

    min += offset;
    if (min >= 60) {
        min = min % 60;
        if (min < 10) {
            min = '0' + String(min);
        }
        hour += 1;
    }

    time = [hour, min].join(':');
    return time;
}

/**
 * 将时间从字符串转为long型
 * @param timeStr
 */
function getLongTime(timeStr) {
    var list = timeStr.split(':').map(function (i, idx) {
        if (idx === 0) {
            return +(Number(i) * 60);
        }
        return +i;
    });

    return list[0] + list[1];
}

/**
 * 将时间从long转为字符串
 * @param longTime
 */
function getStrTime(longTime) {
    var hour, min;
    longTime = longTime.split(':');
    hour = longTime[0];
    min = longTime[1];
    if (min >= 60) {
        min = min % 60;
        if (min < 10) {
            min = '0' + String(min);
        }
        hour += 1;
    }
    return [hour, min].join(':');
}

/**
 *
 * @param longTime
 * @param step  单位：分钟
 */
function addTime(longTime, step) {
    return getStrTime(getLongTime(longTime) + step);
}


/*
 *   比较时间, 送餐时间为开车前35分钟之外才允许选择
 *   arriveTime 送达时间
 *   address 收货地址 0:候车室 1:火车上
 *   step: 35
 */
function compareTime(arriveTime, address, step, date) {
    var aboartTime = getLongTime(route.aboardTime),
        currentTime = date.getHours() * 60 + date.getMinutes();
    arriveTime = getLongTime(arriveTime);

    // 已发车
    if (currentTime > aboartTime) {
        return `<p>${route.trip}已于${route.aboardTime}分发车，无法下单</p>`.trim();
    }

    // 距离发车时间不足35分钟
    if (currentTime > (aboartTime - 35 )) {
        return `<p>距${route.trip}次发车时间不足${step}分钟，无法保证配送，谢绝下单。</p>`.trim();
    }

    // 0:候车室
    if (address === 0) {
        //判断预约时间

        // 预约时间大于发车时间
        if (arriveTime > aboartTime) {
            return `<p>${route.trip}已于${route.aboardTime}分发车，无法下单</p>`.trim();
        }

        // 预约时间在发车时间15分钟之内
        if (arriveTime > (aboartTime - 15 )) {
            return `<p>预约时间距${route.trip}次发车时间不足15分钟，无法保证充足时间上车，谢绝下单。</p>`.trim();
        }
    }

    return null;
}

// 提交数据
$('a#submit').click(function () {
    var type = $(':checked').attr('id'),
        user_name = $('#username').val().trim(),
        phone_no = $('#phone').val().trim(),
        phone_reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
        // address = $('#location-select').data('deliveraddressid'),
        address = $('#location-select').val(),
        date = new Date(),
        hour = date.getHours(),
        min = date.getMinutes(),
        data = {merchantId: sessionStorage.merchantId},
        re = /[^\u4e00-\u9fa5]/,
        time,
        confirm_str,
        afterTime = 35,
        shouhuodizhi,   // 0 为候车室，1为火车上
        endTime,
        routeData;

    // 姓名检测
    if (user_name.length === 0) {
        return $.toast('请输入联系人姓名', 'forbidden');
    }
    if (re.test(user_name)) {
        return $.toast('姓名只能为中文', 'forbidden');
    }
    data['customerName'] = user_name;

    // 电话号码检测
    if (!phone_reg.test(phone_no)) {
        return $.toast('请输入有效的手机号码', 'forbidden')
    }
    data['customerPhoneNo'] = phone_no;
    data['deliverType'] = 16002; // 设置配送方式
    data['listProduct'] = productList; // 设置购买的产品

    // typeId = '#' + type;
    if (type === 'delivery') {
        // type = 16002; // 16002为配送
        // 送餐位置检测
        if (!address) {
            return $.toast('请选择收货位置', 'forbidden')
        }
        data['deliverAddress'] = address;

        // 送达时间
        // var $rtime = $('#receipt-time');
        // timeId = '#' + $rtime.find(':checked').attr('id');
        time = $('#receipt-time').find(':checked').parents('label').find('span.font-orange').text();
        if (time === '20') {
            //after 20 minutes
            data['latestServiceTime'] = getTime(date, 20);
        } else {
            //  user choise time > current time + 20 minutes;
            //user choice time
            data['latestServiceTime'] = time;
        }
        confirm_str = '送餐时间为:' + data['latestServiceTime'];
        shouhuodizhi = 0;
    } else {
        // 自提时间检测
        // var $time = $('#time');
        // timeId = '#' + $time.find(':checked').attr('id');
        // time = $('#time').find(':checked').parents('label').find('span.font-orange').text();
        // if (time === 10) {
        //     afterTime = 10;
        // }
        // data['latestServiceTime'] = getTime(time, 10, hour, min);
        // confirm_str = '取货时间为:' + data['latestServiceTime'];
        // type = 16001; // 16001为自提

        // 火车上
        address = $('#train-select').val().trim();
        if (address.length === 0) {
            return $.toast('请设置收货位置', 'forbidden');
        } else {
            data['deliverAddress'] = stationName + address;
        }
        data['latestServiceTime'] = $('#train-time').find('.weui-flex__item:last-child').text();
        confirm_str = '送餐时间为:' + data['latestServiceTime'];
        shouhuodizhi = 1;
    }

    // 保存当前用户信息
    // routeData = JSON.parse(JSON.stringify(data));
    // routeData['timeId'] = timeId;
    // routeData['typeId'] = typeId;
    // routeData['afterTime'] = afterTime;

    // 是否存在行程
    // if (!sessionStorage.getItem('route')) {
    //     sessionStorage.Order = JSON.stringify(routeData);
    //     return $.alert('您尚未设置行程，点击确认后开始行程设置', '提示', function () {
    //         return window.location.href = 'route.html';
    //     });
    // }

    // 判断是否已经发车
    var string = compareTime(data['latestServiceTime'], shouhuodizhi, 35, date);
    // 判断发车前时间是否足够
    if (string) {
        return $.modal({
            title: '温馨提示',
            text: string,
            buttons: [
                {
                    className: "color-orange",
                    text: '修改行程',
                    onClick: function () {
                        return jump(shouhuodizhi);
                    }
                }, {
                    text: "确定",
                    className: "primary"
                }
            ]
        });
    } else {
        return Pay(confirm_str, data);
    }
});

function Pay(confirm_str, data) {
    var url = '/RailwayService/order/createOrder';

    $.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(data),
        beforeSend: function () {
            $.showLoading();
        },
        success: function (resp) {
            $.hideLoading();
            if (resp.success) {
                var data = resp.data;
                setTimeout(function () {
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId": data.appId,     //公众号名称，由商户传入
                            "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数
                            "nonceStr": data.nonceStr, //随机串
                            "package": data['packAge'],
                            "signType": data.signType,         //微信签名方式：
                            "paySign": data.paySign //微信签名
                        },
                        function (res) {
                            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                            if (res['err_msg'] === "get_brand_wcpay_request:ok") {
                                $.toast('支付成功', "success");
                                setTimeout(function () {
                                    sessionStorage.setItem('orderId', data.orderId);
                                    window.location.href = '/RailwayService/wechat/orderDetail.html';
                                }, 2500);
                            } else {
                                $.toast('支付失败', 'cancel');
                            }
                        }
                    );
                }, 300);
            } else {
                $.toast(resp.message, "forbidden");
            }
        },
        error: function (xml) {
            $.hideLoading();
            $.toast(xml.statusText, "forbidden");
        }
    })

    // $.confirm(confirm_str, "<span style='font-weight:bold;'>确认支付?</span>", function () {});
}

// 解决安卓虚拟键盘问题
var oHeight = $(document).height(); //屏幕当前的高度
$(window).resize(function () {
    if ($(document).height() !== oHeight) {
        $(".footer-wrap").css("display", "none");
    } else {
        $(".footer-wrap").css("display", "block");
    }
});

// 小推车
$("#location-select,#last-time,#time-select,#train-select").click(function () {
    document.activeElement.blur();
    $('.pay-mask').fadeIn('fast');
});

// 车上详细座位
// $('#train-select').click(function () {
//     $.modal({
//         title: `请输入您车次<a href="javascript:jump();" class="color-orange">${route.trip}</a>的座位位置`,
//         text: `
//             <input type="number" class="weui-input weui-prompt-input" id="weui-prompt-car" placeholder="输入车厢编号">
//             <input type="text" class="weui-input weui-prompt-input" id="weui-prompt-seat" placeholder="输入座位编号" onkeyup="this.value=this.value.toUpperCase();">`.trim(),
//         buttons: [
//             {
//                 text: "取消",
//                 className: "default"
//             },
//             {
//                 text: "确定",
//                 onClick: function () {
//                     var car = $('#weui-prompt-car').val().trim(),
//                         num = $('#weui-prompt-seat').val().trim();
//                     if (car.length === 0 || num.length === 0) {
//                         $.toast('请完成设置', 'text');
//                         return false;
//                     }
//                     $('#train-select').val(route.trip + '次' + car + '车' + num + '号');
//                 }
//             },
//         ]
//     });
// });

function jump(type) {
    if (type === 0) {
        type = 'delivery';
    } else {
        type = 'self_take';
    }
    $select = $('#location-select'),
        $input = $('#receipt-time').find(':checked'),
        data = {
            customerName: $('#username').val(),
            customerPhoneNo: $('#phone').val(),
            address: {
                val: $select.val(),
                deliverAddressId: $select.data('deliveraddressid')
            },
            time: {
                checkId: '#' + $input.attr('id'),
                val: $input.parents('label').find('span.font-orange').text()
            },
            seat: $('#train-select').val()
        };

    sessionStorage.setItem('init', JSON.stringify(
        {
            url: 'payOrder.html',
            failed: 'payOrder.html',
            pass: true,
            data: data,
            type: '#' + type
        }
    ));
    window.location.href = 'route.html';
}

$(document).on('click', 'a.close-picker', function () {
    $('.pay-mask').fadeOut('fast');
});

/**
 *  快速生成一个数字数组
 * @param start 起始位置
 * @param stop 结束位置
 * @param step 步长
 */
function getArray(start, stop, step) {
    step = step || 1;
    var array = [];
    for (var i = start; i < stop; i += step) {
        array.push(i);
    }

    return array;
}

$("#train-select").picker({
    payOrder: true,
    title: "请选择您的座位",
    cols: [
        {
            textAlign: 'center',
            values: getArray(1, 17).map(function (i) {
                if (i < 10) {
                    i = '0' + i;
                }
                return i;
            })
        }, {
            textAlign: 'center',
            values: ['车']
        }, {
            textAlign: 'center',
            values: getArray(1, 21).map(function (i) {
                if (i < 10) {
                    i = '0' + i;
                }
                return i;
            })
        }, {
            textAlign: 'center',
            values: ['A', 'B', 'C', 'D', 'F']
        }, {
            textAlign: 'center',
            values: ['号']
        }
    ],
    onClose: function () {
        $('.pay-mask').fadeOut();
        // $(p.params.input).val(p.value.join(''));
    }
});